import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useGlobalStore } from '@/stores/global'
import { UserRole } from '@/types'

// 路由组件懒加载
const Home = () => import('@/views/Home.vue')
const Questions = () => import('@/views/Questions.vue')
const QuestionDetail = () => import('@/views/QuestionDetail.vue')
const SubmissionDetail = () => import('@/views/SubmissionDetail.vue')
const Contests = () => import('@/views/Contests.vue')
const ContestDetail = () => import('@/views/ContestDetail.vue')
const RankDetail = () => import('@/views/RankDetail.vue')
const Resources = () => import('@/views/Resources.vue')
const Profile = () => import('@/views/Profile.vue')
const Progress = () => import('@/views/Progress.vue')
const Favorites = () => import('@/views/Favorites.vue')
const Notes = () => import('@/views/Notes.vue')
const Solutions = () => import('@/views/Solutions.vue')
const Ebooks = () => import('@/views/Ebooks.vue')
const EbookDetail = () => import('@/views/EbookDetail.vue')
const Projects = () => import('@/views/Projects.vue')
const ProjectDetail = () => import('@/views/ProjectDetail.vue')
const Courses = () => import('@/views/Courses.vue')
const CourseDetail = () => import('@/views/CourseDetail.vue')
const Login = () => import('@/views/Login.vue')
const Register = () => import('@/views/Register.vue')
const ResetPassword = () => import('@/views/ResetPassword.vue')
const NotFound = () => import('@/views/NotFound.vue')

// 资源提交相关页面
const SubmitResource = () => import('@/views/SubmitResource.vue')
const CreateCourse = () => import('@/views/CreateCourse.vue')
const CreateEbook = () => import('@/views/CreateEbook.vue')

// 管理员页面
const AdminDashboard = () => import('@/views/admin/Dashboard.vue')
const AdminUsers = () => import('@/views/admin/Users.vue')
const AdminQuestions = () => import('@/views/admin/Questions.vue')
// const AdminCreateQuestion = () => import('@/views/admin/CreateQuestion.vue')
const AdminEditQuestion = () => import('@/views/admin/EditQuestion.vue')
const AdminContests = () => import('@/views/admin/Contests.vue')
const AdminSettings = () => import('@/views/admin/Settings.vue')
const AdminAudit = () => import('@/views/admin/Audit.vue')

// 项目相关页面（已合并到学习资源中）
// const ProjectList = () => import('@/views/ProjectList.vue')
// const ProjectDetail = () => import('@/views/ProjectDetail.vue')
const CreateProject = () => import('@/views/CreateProject.vue')

const CreateQuestion = () => import('@/views/CreateQuestion.vue')

// 积分中心
const PointsCenter = () => import('@/views/PointsCenter.vue')

// AI对话页面
const AIChat = () => import('@/views/AIChat.vue')

// 每日一题页面
const DailyQuestionHistory = () => import('@/views/DailyQuestionHistory.vue')

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      requireAuth: false
    }
  },
  {
    path: '/questions',
    name: 'Questions',
    component: Questions,
    meta: {
      title: '题库',
      requireAuth: false,
    }
  },
  {
    path: '/questions/:id',
    name: 'QuestionDetail',
    component: QuestionDetail,
    meta: {
      title: '题目',
      requireAuth: false,
      hideFooter: true
    }
  },
  {
    path: '/submission/:id',
    name: 'SubmissionDetail',
    component: SubmissionDetail,
    meta: {
      title: '提交详情',
      requireAuth: false,
      hideFooter: true
    }
  },
  {
    path: '/contests',
    name: 'Contests',
    component: Contests,
    meta: {
      title: '竞赛',
      requireAuth: false
    }
  },
  {
    path: '/contests/:id',
    name: 'ContestDetail',
    component: ContestDetail,
    meta: {
      title: '竞赛详情',
      requireAuth: true
    }
  },
  {
    path: '/ranking',
    name: 'Ranking',
    component: RankDetail,
    meta: {
      title: '排行榜',
      requireAuth: false
    }
  },
  {
    path: '/resources',
    name: 'Resources',
    component: Resources,
    meta: {
      title: '学习资源',
      requireAuth: false
    }
  },
  {
    path: '/submit-resource',
    name: 'SubmitResource',
    component: SubmitResource,
    meta: {
      title: '提交资源',
      requireAuth: true
    }
  },
  {
    path: '/courses/create',
    name: 'CreateCourse',
    component: CreateCourse,
    meta: {
      title: '创建课程',
      requireAuth: true
    }
  },
  {
    path: '/ebooks/create',
    name: 'CreateEbook',
    component: CreateEbook,
    meta: {
      title: '上传电子书',
      requireAuth: true
    }
  },
  {
    path: '/ebooks/:id',
    name: 'EbookDetail',
    component: EbookDetail,
    meta: {
      title: '电子书详情',
      requireAuth: false
    }
  },
  {
    path: '/projects/:id',
    name: 'ProjectDetail',
    component: ProjectDetail,
    meta: {
      title: '项目详情',
      requireAuth: false
    }
  },
  {
    path: '/courses/:id',
    name: 'CourseDetail',
    component: CourseDetail,
    meta: {
      title: '课程详情',
      requireAuth: false
    }
  },
  {
    path: '/profile/:id',
    name: 'Profile',
    component: Profile,
    meta: {
      title: '个人中心',
      requireAuth: false
    }
  },
  {
    path: '/my_progress/:id',
    name: 'Progress',
    component: Progress,
    meta: {
      title: '学习进度',
      requireAuth: true
    }
  },
  {
    path: '/favorites/:id',
    name: 'Favorites',
    component: Favorites,
    meta: {
      title: '我的收藏',
      requireAuth: true
    }
  },
  {
    path: '/notes/:id',
    name: 'Notes',
    component: Notes,
    meta: {
      title: '我的笔记',
      requireAuth: true
    }
  },
  {
    path: '/solutions/:id',
    name: 'Solutions',
    component: Solutions,
    meta: {
      title: '题解',
      requireAuth: false
    }
  },
  {
    path: '/ebooks/:id',
    name: 'Ebooks',
    component: Ebooks,
    meta: {
      title: '电子书',
      requireAuth: true
    }
  },
  // 项目相关路由已合并到学习资源中
  // {
  //   path: '/projects',
  //   name: 'ProjectList',
  //   component: ProjectList,
  //   meta: {
  //     title: '项目广场',
  //     requireAuth: false
  //   }
  // },
  // {
  //   path: '/projects/:id',
  //   name: 'ProjectDetail',
  //   component: ProjectDetail,
  //   meta: {
  //     title: '项目详情',
  //     requireAuth: false
  //   }
  // },
  // {
  {
    path: '/projects/create',
    name: 'CreateProject',
    component: CreateProject,
    meta: {
      title: '创建项目',
      requireAuth: true
    }
  },
  {
    path: '/questions/create',
    name: 'CreateQustion',
    component: CreateQuestion,
    meta: {
      title: '创建题目',
      requireAuth: true
    }
  },
  //   meta: {
  //     title: '创建项目',
  //     requireAuth: true
  //   }
  // },
  {
    path: '/my_projects/:id',
    name: 'Projects',
    component: Projects,
    meta: {
      title: '我的项目',
      requireAuth: true
    }
  },
  {
    path: '/courses/:id',
    name: 'Courses',
    component: Courses,
    meta: {
      title: '我的课程',
      requireAuth: true
    }
  },
  {
    path: '/course/:id',
    name: 'CourseDetail',
    component: () => import('@/views/CourseDetail.vue'),
    meta: {
      title: '课程详情',
      requireAuth: false
    }
  },
  {
    path: '/points',
    name: 'PointsCenter',
    component: PointsCenter,
    meta: {
      title: '积分中心',
      requireAuth: true
    }
  },
  {
    path: '/ai-chat',
    name: 'AIChat',
    component: AIChat,
    meta: {
      title: 'AI智能助手',
      requireAuth: true,
      hideFooter: true
    }
  },
  {
    path: '/daily-question/history',
    name: 'DailyQuestionHistory',
    component: DailyQuestionHistory,
    meta: {
      title: '每日一题历史',
      requireAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录',
      requireAuth: false,
      hideForAuth: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      title: '注册',
      requireAuth: false,
      hideForAuth: true
    }
  },
  {
    path: '/reset-password',
    name: 'ResetPassword',
    component: ResetPassword,
    meta: {
      title: '重置密码',
      requireAuth: false,
      hideForAuth: true
    }
  },
  // 管理员路由
  {
    path: '/admin',
    redirect: '/admin/dashboard',
    meta: {
      requireAuth: true,
      roles: [UserRole.ADMIN]
    }
  },
  {
    path: '/admin/dashboard',
    name: 'AdminDashboard',
    component: AdminDashboard,
    meta: {
      title: '管理后台',
      requireAuth: true,
      roles: [UserRole.ADMIN]
    }
  },
  {
    path: '/admin/users',
    name: 'AdminUsers',
    component: AdminUsers,
    meta: {
      title: '用户管理',
      requireAuth: true,
      roles: [UserRole.ADMIN]
    }
  },
  {
    path: '/admin/questions',
    name: 'AdminQuestions',
    component: AdminQuestions,
    meta: {
      title: '题目管理',
      requireAuth: true,
      roles: [UserRole.ADMIN, UserRole.TEACHER]
    }
  },
  // {
  //   path: '/admin/questions/create',
  //   name: 'AdminCreateQuestion',
  //   component: AdminCreateQuestion,
  //   meta: {
  //     title: '创建题目',
  //     requireAuth: true,
  //     roles: [UserRole.ADMIN, UserRole.TEACHER]
  //   }
  // },
  {
    path: '/admin/questions/:id/edit',
    name: 'AdminEditQuestion',
    component: AdminEditQuestion,
    meta: {
      title: '编辑题目',
      requireAuth: true,
      roles: [UserRole.ADMIN, UserRole.TEACHER]
    }
  },
  {
    path: '/admin/contests',
    name: 'AdminContests',
    component: AdminContests,
    meta: {
      title: '竞赛管理',
      requireAuth: true,
      roles: [UserRole.ADMIN, UserRole.TEACHER]
    }
  },
  {
    path: '/admin/settings',
    name: 'AdminSettings',
    component: AdminSettings,
    meta: {
      title: '系统设置',
      requireAuth: true,
      roles: [UserRole.ADMIN]
    }
  },
  {
    path: '/admin/audit',
    name: 'AdminAudit',
    component: AdminAudit,
    meta: {
      title: '审核管理',
      requireAuth: true,
      roles: [UserRole.ADMIN]
    }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面不存在'
    }
  }
]

const router = createRouter({
  history: createWebHistory('/'),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  const globalStore = useGlobalStore()

  // 设置页面标题
  const title = to.meta.title as string
  if (title) {
    globalStore.setPageTitle(title)
  }

  // 检查是否需要认证
  if (to.meta.requireAuth) {
    // 检查登录状态
    const isAuthenticated = await authStore.checkLogin()
    
    if (!isAuthenticated) {
      // 未登录，跳转到登录页
      next({
        name: 'Login',
        query: { redirect: to.fullPath }
      })
      return
    }

    // 检查角色权限
    if (to.meta.roles && Array.isArray(to.meta.roles)) {
      const userRole = authStore.user?.role
      const allowedRoles = to.meta.roles as UserRole[]
      
      if (!userRole || !allowedRoles.includes(userRole)) {
        // 权限不足，跳转到首页
        globalStore.addToast({
          type: 'error',
          title: '访问权限不足'
        })
        next({ name: 'Home' })
        return
      }
    }
  }

  // 已登录用户访问登录/注册页面，跳转到首页
  if (to.meta.hideForAuth && authStore.isAuthenticated) {
    next({ name: 'Home' })
    return
  }

  // 处理用户个人页面的权限检查
  if (to.name === 'Progress' || to.name === 'Favorites' || to.name === 'Notes' || 
      to.name === 'Ebooks' || to.name === 'Projects' || to.name === 'Courses') {
    const userId = parseInt(to.params.id as string)
    const currentUserId = authStore.user?.id
    
    // 只能访问自己的个人页面或管理员可以访问所有页面
    if (currentUserId !== userId && !authStore.isAdmin) {
      globalStore.addToast({
        type: 'error',
        title: '无权访问该页面'
      })
      next({ name: 'Home' })
      return
    }
  }

  next()
})

// 路由错误处理
router.onError((error) => {
  console.error('Router error:', error)
  const globalStore = useGlobalStore()
  globalStore.setError({
    message: '路由导航出错',
    code: -1
  })
})

export default router

